<template>
  <el-main>
    <h1>医生登录</h1>
    <el-form ref="ruleForm" :model="ruleForm" :rules="rules" class="demo-ruleForm" label-width="100px" status-icon>
      <el-form-item label="用户名" prop="username">
        <el-input v-model="ruleForm.username" autocomplete="off" type="text"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="ruleForm.password" autocomplete="off" show-password type="password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">登录</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </el-main>
</template>

<script>
export default {
  name: "Login",
  data() {
    return {
      ruleForm: {
        username: '',
        password: ''
      },
      rules: {
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'}
        ]
      }
    };
  },
  created() {
    this.$store.commit("LOGOUT");
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$axios({
            // 通过axios向后端发送请求
            method: "post",
            url: "/doctor/login",
            params: {
              username: this.ruleForm.username, // 传递用户名
              password: this.ruleForm.password // 传递用户密码
            }
          }).then(res => {
            // console.log(res);
            var data = res.data;
            if (data.code == 200) {
              // 登录成功
              this.$store.commit("SET_TOKEN", data.data.id);
              this.$message({
                message: data.data.realName + "登陆成功",
                type: "success"
              });
              this.$router.push({path: "/questionnaire"});
            } else {
              this.$message({
                message: data.msg,
                type: "error"
              });
            }
          });
        } else {
          this.$message({
            message: "信息不全",
            type: "error"
          });
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  }
}
</script>
